package com.xiaoke.java3;

/**
 * @author yd
 * @version 1.0
 * @date 2022/1/18 22:47
 */
public class StringBuilderTest {
    //s1的声明方式是线程安全的
    public static void method1(){
        //线程内部创建的,属于局部变量，方法结束，变量消亡
        StringBuilder s = new StringBuilder();
        s.append("a");
        s.append("b");

    }
    //stringBuilder是线程不安全的,操作的是共享数据
    public static void method2(StringBuilder stringBuilder){
        stringBuilder.append("a");
        stringBuilder.append("b");
    }
    /**
     * 同时并发的执行，会出现线程不安全的问题
     */
    public static void method03() {
        StringBuilder stringBuilder = new StringBuilder();
        new Thread(() -> {
            stringBuilder.append("a");
            stringBuilder.append("b");
        }, "t1").start();

        method2(stringBuilder);
        System.out.println(stringBuilder);
    }
    //这个也是线程不安全的,因为有返回值，有可能被其他程序调用
    public static StringBuilder method4(){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("a");
        stringBuilder.append("b");
        return stringBuilder;
    }
    // StringBuilder是线程安全的，return String会新创一个对象
    public static String method05() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("a");
        stringBuilder.append("b");
        return stringBuilder.toString();
    }

    public static void main(String[] args) {

        method03();


    }

}
